package com.haiyou.dc.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {


    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {

        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //创建服务
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5
                , 10
                , 3
                , TimeUnit.SECONDS
                , new LinkedBlockingQueue<>()
                , threadFactory
                , new ThreadPoolExecutor.AbortPolicy());

        TestCallable testCallable1 = new TestCallable("http://a2.att.hudong.com/08/72/01300000165476121273722687045.jpg", "aa.jpg");
        TestCallable testCallable2 = new TestCallable("http://www.togogo.net/image/zhuanti/redhat/cup3.png", "aa.png");

//        List<TestCallable> list = new ArrayList();
//        list.add(testCallable1);
//        list.add(testCallable2);
//
//        for (TestCallable testCallable : list) {
//            threadPoolExecutor.submit(testCallable);
//        }

//
        //提交任务
        Future<Boolean> s1 = threadPoolExecutor.submit(testCallable1);
        Boolean r1 = s1.get();

        //提交任务
        Future<Boolean> s2 = threadPoolExecutor.submit(testCallable2);
        Boolean r2 = s2.get();

        System.out.println(r1);
        System.out.println(r2);

        //关闭服务
        threadPoolExecutor.shutdown();
    }
}
